package com.xiyue.leaspring.service.impl;

import com.xiyue.leaspring.dao.IMemberDAO;
import com.xiyue.leaspring.dao.IRoleDAO;
import com.xiyue.leaspring.po.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户接口实现类
 *
 * @author xiyue
 * @version 1.0
 * @date 2021/04/18 18:59:10
 */
@Service(value = "userDetailService")//注解配置,此名称要在spring.xml中使用
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IMemberDAO memberDAO;//注入用户数据操作接口

    @Autowired
    private IRoleDAO roleDAO;//注入角色操作接口

    @Override
    public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException {
        Optional<Member> optionalMember = this.memberDAO.findById(username);//根据用户ID进行查询
        if(!optionalMember.isPresent()){//用户信息不存在
            throw new UsernameNotFoundException("用户“"+
                    username+"”信息不存在,无法进行登录。");
        }
        Member member = optionalMember.get();//获取用户对象
        //用户对应的所有角色需要通过GrantedAuthority集合保存
        List<GrantedAuthority> allGrantedAuthority = new ArrayList<>();
        Set<String> allRoles= this.roleDAO.findAllByMember(username);//获取用户角色信息
        Iterator<String> roleIter = allRoles.iterator();//迭代输出角色信息
        while (roleIter.hasNext()){
            allGrantedAuthority.add(new SimpleGrantedAuthority(roleIter.next()));
        }
        boolean enabled = member.getEnabled().equals(1);//判断用状态
        UserDetails userDetails = new User(username,member.getPassword(),enabled
            ,true,true,true,allGrantedAuthority);

        return userDetails;//返回UserDetails对象
    }
}
